package com.istock.union.controller.security;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.istock.base.spring.dynamicLoad.PropertyStaticLoader;
import com.istock.union.model.IndexMenu;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.model.MenuInfo;
import com.istock.union.user.model.SSOUser;
import com.istock.union.user.service.MenuInfoService;
import com.istock.union.user.service.UserInfoService;
import com.istock.union.user.util.Configs;
import com.istock.union.user.utils.WebCommonUtils;
import com.istock.union.util.MessageUtils;

@Controller
@RequestMapping("/s")
public class IndexController {

	@Autowired
	private MenuInfoService menuInfoService;

	@Autowired
	private UserInfoService userInfoService;
	
	@Value("${sso.token.name:logintoken}")
	private String tokenName = "";
	
	@RequestMapping("index")
	public String toIndex(ModelMap model , HttpServletRequest request){
		//进入index页面,需要渲染菜单和当前登录用户的信息
		//只要进入index,就需要加载信息
		
		model.put("storeType", PropertyStaticLoader.getInstance().findProperty("sso.token.storeType", "cookie"));
		model.put("tokenName", tokenName);
		
		SSOUser ssoUser = SSOClientUtils.getInstance().findCurrentUser();
		model.put("user", ssoUser);
		
		List<MenuInfo> menuList = null;
		if(userInfoService.isAdmin(ssoUser)){
			menuList = menuInfoService.findAllMenu();
		}else{
			//使用当前的身份ID
			menuList = menuInfoService.findMenuInfoByCredentialId(ssoUser.getCredentialId());
		}
		model.put("menuList", convertMenu(menuList , request.getContextPath()));
		
		String menuShowType = Configs.getInstance().findByKey("MENU_SHOW_TYPE");
		if(StringUtils.equalsIgnoreCase(menuShowType, "top")) {
			return "index-topnav";
		}
		
		return "index";
	}
	
	@RequestMapping("main")
	public String toMain(){
		System.out.println("======================================="+MessageUtils.message("not.null", null));
		return "main";
	}
	
	/**menuList 是按照parentId排序过的一个平面列表
	 * 将menuList组装成一个带有children的列表
	 * @param menuList
	 * @return
	 */
	private List<IndexMenu> convertMenu(List<MenuInfo> menuList , String contextPath){
		if(menuList != null){
			List<IndexMenu> result = new ArrayList<IndexMenu>();
			
			for(MenuInfo menuInfo : menuList){
				IndexMenu menuInfoVO = new IndexMenu();
				menuInfoVO.setMenuName(menuInfo.getMenuName());
				if(StringUtils.isNotBlank(menuInfo.getUrl())) {
					if(menuInfo.getUrl().toLowerCase().startsWith("http")) {
						//如果以http开头,直接使用url
						menuInfoVO.setUrl(menuInfo.getUrl());
					}else if(menuInfo.getUrl().startsWith("/")){
						//如果以/开头,直接使用url
						menuInfoVO.setUrl(menuInfo.getUrl());
					}else {
						//如果没有/也没有http开头,拼接contextPath
						menuInfoVO.setUrl(WebCommonUtils.contactPath(contextPath, menuInfo.getUrl()));
					}
				}else {
					menuInfoVO.setUrl(menuInfo.getUrl());
				}
				menuInfoVO.setId(menuInfo.getId());
				menuInfoVO.setIcon(menuInfo.getIcon());
				if("0".equalsIgnoreCase(menuInfo.getParentId())){
					//因为排序过,parentId为0,则直接在
					result.add(menuInfoVO);
				}else{
					IndexMenu targetMenuInfo = findMenuById(result , menuInfo.getParentId());
					if(targetMenuInfo != null){
						targetMenuInfo.getChildren().add(menuInfoVO);
					}
				}
			}
			
			return result;
		}
		return null;
	}

	/**从menuList中,选择id的menu对象
	 * 包含子节点的过滤
	 * @param menuList
	 * @param id
	 * @return
	 */
	private IndexMenu findMenuById(List<IndexMenu> menuList , String id){
		if(menuList != null){
			for(IndexMenu menuInfo : menuList){
				if(menuInfo.getId().equalsIgnoreCase(id)){
					return menuInfo;
				}
				if(menuInfo.getChildren() != null && menuInfo.getChildren().size()>0){
					IndexMenu childResult = findMenuById(menuInfo.getChildren() , id);
					if(childResult != null){
						return childResult;
					}
				}
			}
		}
		return null;
	}
}
